package rj.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
@WebServlet(name="CountServlet",urlPatterns = "/CountServlet")
public class CountServlet extends HttpServlet {
    public void init() throws ServletException {
        int count = 0; // 给次数设置一个初始值 0
        ServletContext context = getServletContext();
        // 将 0 存入到 ServletContext 中
        context.setAttribute("count", count);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        // 将原来的次数 count 从 ServletContext 中取出来
        Integer count = (Integer) context.getAttribute("count");
        if (count == null) {
            count = 0; // 如果 count 为 null，则初始化为 0（理论上不应该发生，除非 ServletContext 被重置）
        }
        count += 1;
        // 存入到 ServletContext 中
        context.setAttribute("count", count);

        // 向页面输出欢迎光临!
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<h1>欢迎光临本网站! 这是您第" + count + "次访问</h1>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}